package dht.statistics;

import java.util.HashMap;
import java.util.Vector;

import dht.data.Access;
import dht.data.AccessType;

public class DhtStatistics {
	public static int totalAccessCount;
	public static int totalAccessProcessedCount;
	public static Vector<MovementStatistics> movementStatistics;
	public static HashMap<AccessType, AccessStatistics> accessStatistics;
	public static HashMap<Integer, ServerStatistics> serverStatistics;

	// for debug
	public static int rank1 = 0;
	public static int ranktotal = 0;

	public static void initialize(int serverNum) {
		totalAccessCount = 0;
		totalAccessProcessedCount = 0;
		movementStatistics = new Vector<MovementStatistics>();
		accessStatistics = new HashMap<AccessType, AccessStatistics>();
		serverStatistics = new HashMap<Integer, ServerStatistics>();
		for (AccessType accessType : AccessType.values()) {
			accessStatistics.put(accessType, new AccessStatistics(accessType));
		}
		for (int i = 0; i <= serverNum; ++i) {
			serverStatistics.put(i, new ServerStatistics(i));
		}
	}

	public static void dump() {
		for (int serverId = 0; serverId < serverStatistics.size(); ++serverId) {
			System.out.println(serverStatistics.get(serverId).toString());
		}

		for (MovementStatistics movement : movementStatistics) {
			System.out.println(movement.toString());
		}

		for (AccessType accessType : accessStatistics.keySet()) {
			System.out.println(accessStatistics.get(accessType).toString());
		}

		System.out.println("totalAccessCount: " + totalAccessCount);
		System.out.println("totalAccessProcessedCount: "
				+ totalAccessProcessedCount);
		System.out.println();
	}

	public static void movementReport(double startTime, int fromId,
			int fromVnodeCount, double fromLoad, int toId, int toVnodeCount,
			double toLoad) {
		movementStatistics.add(new MovementStatistics(startTime, fromId,
				fromVnodeCount, fromLoad, toId, toVnodeCount, toLoad));
	}

	public static void accessReport(Access access) {
		accessStatistics.get(access.accessType).updateStatistics(access);
	}

	public static void clientReport(int clientId, int clientUpdateCount) {
		serverStatistics.get(clientId).clientUpdateCount += clientUpdateCount;
	}

	public static void serverReport(int serverId, int updateCount,
			int updateRejectCount, int readCount, int writeCount) {
		serverStatistics.get(serverId).updateCount += updateCount;
		serverStatistics.get(serverId).updateRejectCount += updateRejectCount;
		serverStatistics.get(serverId).readCount += readCount;
		serverStatistics.get(serverId).writeCount += writeCount;
	}

	public static void serverCpuReport(int serverId, double idleTime,
			double processTime, double lastActiveTime) {
		serverStatistics.get(serverId).idleTime += idleTime;
		serverStatistics.get(serverId).processTime += processTime;
		serverStatistics.get(serverId).lastActiveTime = lastActiveTime;
		serverStatistics.get(serverId).cpuReportCount++;
	}
}
